const { asyncHandler } = require('../middleware/errorHandler');
const { success, error, paginate, paginateResponse } = require('../utils/common');
const Course = require('../models/Course');
const User = require('../models/User');
const Category = require('../models/Category');
const CourseUser = require('../models/CourseUser');
const { Op } = require('sequelize');

class CourseController {
  /**
   * 获取课程列表
   */
  static getCourses = asyncHandler(async (req, res) => {
    const { 
      page = 1, 
      limit = 10, 
      category_id, 
      teacher_id, 
      status = 'published',
      is_free,
      is_recommend,
      is_hot,
      keyword,
      sort = 'created_at',
      order = 'desc'
    } = req.query;

    const { offset, limit: pageLimit } = paginate(page, limit);

    // 构建查询条件
    const where = {};
    
    if (category_id) where.category_id = category_id;
    if (teacher_id) where.teacher_id = teacher_id;
    if (status) where.status = status;
    if (is_free !== undefined) where.is_free = is_free === 'true';
    if (is_recommend !== undefined) where.is_recommend = is_recommend === 'true';
    if (is_hot !== undefined) where.is_hot = is_hot === 'true';
    
    if (keyword) {
      where[Op.or] = [
        { title: { [Op.like]: `%${keyword}%` } },
        { description: { [Op.like]: `%${keyword}%` } }
      ];
    }

    // 构建排序条件
    const orderClause = [[sort, order.toUpperCase()]];

    // 查询课程
    const { count, rows: courses } = await Course.findAndCountAll({
      where,
      include: [
        {
          model: User,
          as: 'teacher',
          attributes: ['id', 'username', 'nickname', 'avatar', 'bio']
        },
        {
          model: Category,
          as: 'category',
          attributes: ['id', 'name', 'description']
        }
      ],
      attributes: [
        'id', 'title', 'description', 'cover', 'price', 'original_price',
        'duration', 'lessons_count', 'students_count', 'views_count',
        'likes_count', 'status', 'is_free', 'is_recommend', 'is_hot',
        'tags', 'published_at', 'created_at'
      ],
      order: orderClause,
      offset,
      limit: pageLimit
    });

    // 格式化数据
    const formattedCourses = courses.map(course => ({
      ...course.toJSON(),
      teacher: course.teacher ? {
        id: course.teacher.id,
        username: course.teacher.username,
        nickname: course.teacher.nickname,
        avatar: course.teacher.avatar,
        bio: course.teacher.bio
      } : null,
      category: course.category ? {
        id: course.category.id,
        name: course.category.name,
        description: course.category.description
      } : null
    }));

    res.json(paginateResponse(formattedCourses, count, page, limit));
  });

  /**
   * 获取课程详情
   */
  static getCourseDetail = asyncHandler(async (req, res) => {
    const { id } = req.params;

    const course = await Course.findByPk(id, {
      include: [
        {
          model: User,
          as: 'teacher',
          attributes: ['id', 'username', 'nickname', 'avatar', 'bio', 'email']
        },
        {
          model: Category,
          as: 'category',
          attributes: ['id', 'name', 'description']
        }
      ]
    });

    if (!course) {
      return res.status(404).json(error('课程不存在'));
    }

    // 增加观看次数
    await course.increment('views_count');

    // 格式化数据
    const courseData = {
      ...course.toJSON(),
      teacher: course.teacher ? {
        id: course.teacher.id,
        username: course.teacher.username,
        nickname: course.teacher.nickname,
        avatar: course.teacher.avatar,
        bio: course.teacher.bio
      } : null,
      category: course.category ? {
        id: course.category.id,
        name: course.category.name,
        description: course.category.description
      } : null
    };

    res.json(success(courseData, '获取成功'));
  });

  /**
   * 获取推荐课程
   */
  static getRecommendedCourses = asyncHandler(async (req, res) => {
    const { limit = 6 } = req.query;

    const courses = await Course.findAll({
      where: {
        status: 'published',
        is_recommend: true
      },
      include: [
        {
          model: User,
          as: 'teacher',
          attributes: ['id', 'username', 'nickname', 'avatar']
        }
      ],
      attributes: [
        'id', 'title', 'description', 'cover', 'price', 'original_price',
        'duration', 'lessons_count', 'students_count', 'views_count',
        'is_free', 'created_at'
      ],
      order: [['created_at', 'DESC']],
      limit: parseInt(limit)
    });

    const formattedCourses = courses.map(course => ({
      ...course.toJSON(),
      teacher: course.teacher ? {
        id: course.teacher.id,
        username: course.teacher.username,
        nickname: course.teacher.nickname,
        avatar: course.teacher.avatar
      } : null
    }));

    res.json(success(formattedCourses, '获取成功'));
  });

  /**
   * 获取热门课程
   */
  static getHotCourses = asyncHandler(async (req, res) => {
    const { limit = 6 } = req.query;

    const courses = await Course.findAll({
      where: {
        status: 'published'
      },
      include: [
        {
          model: User,
          as: 'teacher',
          attributes: ['id', 'username', 'nickname', 'avatar']
        }
      ],
      attributes: [
        'id', 'title', 'description', 'cover', 'price', 'original_price',
        'duration', 'lessons_count', 'students_count', 'views_count',
        'is_free', 'created_at'
      ],
      order: [['views_count', 'DESC'], ['students_count', 'DESC']],
      limit: parseInt(limit)
    });

    const formattedCourses = courses.map(course => ({
      ...course.toJSON(),
      teacher: course.teacher ? {
        id: course.teacher.id,
        username: course.teacher.username,
        nickname: course.teacher.nickname,
        avatar: course.teacher.avatar
      } : null
    }));

    res.json(success(formattedCourses, '获取成功'));
  });

  /**
   * 获取我的课程
   */
  static getMyCourses = asyncHandler(async (req, res) => {
    const userId = req.user.id;
    const { page = 1, limit = 10 } = req.query;

    const { offset, limit: pageLimit } = paginate(page, limit);

    // 查询用户购买的课程
    const { count, rows: courseUsers } = await CourseUser.findAndCountAll({
      where: { user_id: userId },
      include: [
        {
          model: Course,
          as: 'course',
          include: [
            {
              model: User,
              as: 'teacher',
              attributes: ['id', 'username', 'nickname', 'avatar']
            }
          ],
          attributes: [
            'id', 'title', 'description', 'cover', 'price', 'original_price',
            'duration', 'lessons_count', 'status', 'created_at'
          ]
        }
      ],
      attributes: [
        'id', 'course_id', 'progress', 'completed_lessons',
        'total_watch_time', 'last_watch_at', 'created_at'
      ],
      order: [['last_watch_at', 'DESC'], ['created_at', 'DESC']],
      offset,
      limit: pageLimit
    });

    // 格式化数据
    const formattedCourses = courseUsers.map(cu => ({
      ...cu.course.toJSON(),
      teacher: cu.course.teacher ? {
        id: cu.course.teacher.id,
        username: cu.course.teacher.username,
        nickname: cu.course.teacher.nickname,
        avatar: cu.course.teacher.avatar
      } : null,
      progress: cu.progress || 0,
      completed_lessons: cu.completed_lessons || 0,
      total_watch_time: cu.total_watch_time || 0,
      last_watch_at: cu.last_watch_at,
      enrolled_at: cu.created_at
    }));

    res.json(paginateResponse(formattedCourses, count, page, limit));
  });
}

module.exports = CourseController; 